package UI;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.DataOutputStream;
import java.net.Socket;

public class ChatRoomUI extends JFrame {
    private JTextArea chatTextArea;
    private JTextField messageField;
    private JButton sendButton;
    private JList<String> userList;
    private DefaultListModel<String> userListModel;
    private Socket socket;
    private String nickname;

    public ChatRoomUI() {
        initFrame();
        setVisible(true);
    }

    public void initFrame(){
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建聊天区域
        chatTextArea = new JTextArea();
        chatTextArea.setEditable(false);
        JScrollPane chatScrollPane = new JScrollPane(chatTextArea);

        // 创建消息输入框和发送按钮
        JPanel inputPanel = new JPanel(new BorderLayout());
        messageField = new JTextField();
        sendButton = new JButton("Send");

        inputPanel.add(messageField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);

        // 创建用户列表
        userListModel = new DefaultListModel<>();
        userList = new JList<>(userListModel);
        JScrollPane userScrollPane = new JScrollPane(userList);

        // 设置布局
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, chatScrollPane, userScrollPane);
        splitPane.setDividerLocation(600);
        getContentPane().add(splitPane, BorderLayout.CENTER);
        getContentPane().add(inputPanel, BorderLayout.SOUTH);

        // 添加发送按钮事件监听器
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });

        // 按Enter键发送消息
        messageField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
        
        // 添加用户列表双击事件监听器，用于私聊
        userList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // 判断是否为双击事件
                if (e.getClickCount() == 2) {
                    // 获取选中的用户索引
                    int selectedIndex = userList.getSelectedIndex();
                    if (selectedIndex != -1) {
                        // 获取选中的用户名
                        String selectedUser = userListModel.getElementAt(selectedIndex);
                        // 不能给自己发私聊消息
                        if (!selectedUser.equals(nickname)) {
                            // 弹出输入框，获取私聊内容
                            String privateMessage = JOptionPane.showInputDialog(ChatRoomUI.this,
                                    "发送私聊消息给 " + selectedUser + ":", "私聊", JOptionPane.PLAIN_MESSAGE);
                            // 发送私聊消息
                            if (privateMessage != null && !privateMessage.trim().isEmpty()) {
                                sendPrivateMessage(selectedUser, privateMessage.trim());
                            }
                        } else {
                            // 提示不能给自己发消息
                            JOptionPane.showMessageDialog(ChatRoomUI.this, "不能给自己发送私聊消息", "提示", JOptionPane.WARNING_MESSAGE);
                        }
                    }
                }
            }
        });

    }

    public ChatRoomUI(String nickname, Socket socket) {
        this();
        setTitle(nickname+"的聊天窗口");
        this.nickname = nickname;
        this.socket = socket;
        new ClentReaderThread(socket,this).start();
    }

    private void sendMessage() {
        String message = messageField.getText().trim();
        if (!message.isEmpty()) {
            //将消息发送给服务器
            try {
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                dos.writeInt(ConstantClient.GROUP_MESSAGE);
                dos.writeUTF(message);
                dos.flush();
                messageField.setText("");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    private void sendPrivateMessage(String toUser, String message) {
        try {
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            dos.writeInt(ConstantClient.PRIVATE_MESSAGE);
            dos.writeUTF(toUser);
            dos.writeUTF(message);
            dos.flush();
            chatTextArea.append("[私聊给 " + toUser + "] " + message + "\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 更新用户列表的方法
    public void updateUserList(String[] users) {
        userListModel.clear();
        for (String user : users) {
            userListModel.addElement(user);
        }
    }

    public void showMsg(String msg) {
        if (!msg.isEmpty()) {
            chatTextArea.append(msg + "\n");
            messageField.setText("");
        }
//        chatTextArea.setCaretPosition(chatTextArea.getText().length());
    }
    
    public void showPrivateMsg(String msg) {
        if (!msg.isEmpty()) {
            chatTextArea.append("[私聊] " + msg + "\n");
        }
    }
}